package com.etoak.service.impl;

import com.etoak.api.DishesService;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.entity.OrderItem;
import com.etoak.mapper.OrderItemMapper;
import com.etoak.service.OrderItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.etoak.vo.OrderDetailVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  服务实现类
 *
 * @author etoak
 * @since 2025-08-28
 */
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {
    @Autowired
    DishesService dishesService;

    @Override
    public List<OrderDetailVO> getDetail(String orderNO) {
        // 1.先根据订单编号查询订单列表
        List<OrderItem> itemList = lambdaQuery().eq(OrderItem::getOrderNo, orderNO).list();

        //hash 方法
        Map<Integer, Integer> dishesIdMap = new HashMap<>();
        itemList.forEach(item -> dishesIdMap.put(item.getDishesId(), item.getDishesNum()));

        // 2.远程调用 /dishes/1,2,3

        List<Integer> dishesIdList = itemList.stream().map(OrderItem::getDishesId).toList();
        ResultVO<List<DishesVO>> resultVO = dishesService.getByIds(dishesIdList);


        //3.封装 List<OrderDetailVO>
        List<OrderDetailVO> detailVOList = new ArrayList<>();
        if (resultVO.getCode().equals(ResultVO.SUCCESS_CODE) && CollectionUtils.isNotEmpty(resultVO.getData())) {
            detailVOList = resultVO.getData().stream().map(dishes -> {
                OrderDetailVO orderDetailVO = new OrderDetailVO();
                orderDetailVO.setOrderNo(orderNO);
                orderDetailVO.setDishesName(dishes.getName());
                orderDetailVO.setDishesNum(dishesIdMap.get(dishes.getId()));

                StringBuffer detail = new StringBuffer();
                detail
                        .append(dishes.getMainName()).append(":").append(dishes.getMainNum()).append("g;")
                        .append(dishes.getMinorName()).append(":").append(dishes.getMinorNum()).append("g;")
                        .append(dishes.getSeasoningName()).append(":").append(dishes.getSeasoningNum()).append("g;");
                orderDetailVO.setDetail(detail.toString());
                return orderDetailVO;
            }).toList();
        }

        return detailVOList;
    }
}
